import React from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import LoadingSpinner from './LoadingSpinner'

interface ProtectedRouteProps {
  children: React.ReactNode
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
  const { isLoggedIn, loading } = useAuth()
  const location = useLocation()

  // 正在加载用户状态
  if (loading) {
    return <LoadingSpinner size="lg" text="正在验证登录状态..." fullScreen />
  }

  // 未登录，重定向到登录页面
  if (!isLoggedIn) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  // 已登录，显示受保护的内容
  return <>{children}</>
}

export default ProtectedRoute
